import state from "@/store";
import router from "@/router/index";
import { routes,newRoutes } from "@/router/index";

function loopRouter(newRoutes,permission) {
    //遍历动态的路由，去除有权限控制且权限没有的路由
    for (let i=0;i<newRoutes.length;i++){
        if(!newRoutes[i].meta.code||permission.indexOf(newRoutes[i].meta.code)>-1){
            console.log("匹配上了")
            if(newRoutes[i].children){
                loopRouter(newRoutes[i].children,permission)
            }
        }else{
            console.log("没有code")
            newRoutes.splice(i,1)
            i--
        }
    }
}
// 取出所有权限值
export function initDynamicRouters1() {
//对路由规则动态添加
    console.log(state.state.permission.permission1)
    loopRouter(newRoutes,state.state.permission.permission1)
    newRoutes.push({
        path: '*',
        name: '404',
        meta: {
            title:"没找到",
            hidden:true
        },
        component: () => import('@/views/layout/errorPage/404.vue')
    })
    routes[0].children = routes[0].children.concat(newRoutes)

    newRoutes.forEach(item=>{
        router.addRoute("Index",item)
    })

}


function loopRouter2(newRoutes,permission) {
    for (let i=0;i<newRoutes.length;i++){
        if(newRoutes[i].meta.code){
            let isHave = true//true表面没有匹配成功的路由
            console.log("有code")
            permission.forEach(item=>{
                if(item.code == newRoutes[i].meta.code){
                    isHave = false
                    newRoutes[i].meta.CRUD = item.CRUD
                    console.log("匹配成功")
                }
            })
            if(isHave){
                console.log("移除")
                newRoutes.splice(i,1)
                i--
            }else{
                if(newRoutes[i].children){
                    loopRouter2(newRoutes[i].children,permission)
                }
            }

        }
    }
}
// 取出所有权限值
export function initDynamicRouters2() {
//对路由规则动态添加
    loopRouter2(newRoutes,state.state.permission.permission2)
    newRoutes.push({
        path: '*',
        name: '404',
        meta: {
            title:"没找到",
            hidden:true
        },
        component: () => import('@/views/layout/errorPage/404.vue')
    })
    routes[0].children = routes[0].children.concat(newRoutes)

    newRoutes.forEach(item=>{
        router.addRoute("Index",item)
    })
    console.log(router)


}
